/* Play music from Bluetooth device

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <inttypes.h>
#include <string.h>

#include "esp_bt_defs.h"
#include "esp_gap_bt_api.h"
#include "esp_hf_client_api.h"
#include "esp_log.h"
#include "esp_peripherals.h"
#include "periph_adc_button.h"
#include "periph_button.h"
#include "periph_touch.h"

#include "audio_element.h"
#include "audio_event_iface.h"
#include "audio_mem.h"
#include "audio_pipeline.h"

#include "bluetooth_service.h"
#include "board.h"
#include "esp_bt.h"
#include "esp_bt_device.h"
#include "esp_bt_main.h"
#include "filter_resample.h"
#include "i2s_stream.h"
#include "raw_stream.h"
#include "user_bt.h"
#include "user_utils.h"

#define HFP_RESAMPLE_RATE 16000

static const char *TAG = "Classic BT";
static int discovery_timeout = BT_AUTO_DISCOVERY_TIMEOUT;

#define HFP_ENABLE
#ifdef HFP_ENABLE
static const char *BT_HF_TAG = "BT_HF";

audio_element_handle_t bt_stream_reader, raw_read; // bt专用的两个elements
static audio_pipeline_handle_t pipeline_d, pipeline_e;
static bool is_get_hfp = true;

const char *c_hf_evt_str[] = {
    "CONNECTION_STATE_EVT",      /*!< connection state changed event */
    "AUDIO_STATE_EVT",           /*!< audio connection state change event */
    "VR_STATE_CHANGE_EVT",       /*!< voice recognition state changed */
    "CALL_IND_EVT",              /*!< call indication event */
    "CALL_SETUP_IND_EVT",        /*!< call setup indication event */
    "CALL_HELD_IND_EVT",         /*!< call held indicator event */
    "NETWORK_STATE_EVT",         /*!< network state change event */
    "SIGNAL_STRENGTH_IND_EVT",   /*!< signal strength indication event */
    "ROAMING_STATUS_IND_EVT",    /*!< roaming status indication event */
    "BATTERY_LEVEL_IND_EVT",     /*!< battery level indication event */
    "CURRENT_OPERATOR_EVT",      /*!< current operator name event */
    "RESP_AND_HOLD_EVT",         /*!< response and hold event */
    "CLIP_EVT",                  /*!< Calling Line Identification notification event */
    "CALL_WAITING_EVT",          /*!< call waiting notification */
    "CLCC_EVT",                  /*!< listing current calls event */
    "VOLUME_CONTROL_EVT",        /*!< audio volume control event */
    "AT_RESPONSE",               /*!< audio volume control event */
    "SUBSCRIBER_INFO_EVT",       /*!< subscriber information event */
    "INBAND_RING_TONE_EVT",      /*!< in-band ring tone settings */
    "LAST_VOICE_TAG_NUMBER_EVT", /*!< requested number from AG event */
    "RING_IND_EVT",              /*!< ring indication event */
};

// esp_hf_client_connection_state_t
const char *c_connection_state_str[] = {
    "disconnected", "connecting", "connected", "slc_connected", "disconnecting",
};

// esp_hf_client_audio_state_t
const char *c_audio_state_str[] = {
    "disconnected",
    "connecting",
    "connected",
    "connected_msbc",
};

/// esp_hf_vr_state_t
const char *c_vr_state_str[] = {
    "disabled",
    "enabled",
};

// esp_hf_service_availability_status_t
const char *c_service_availability_status_str[] = {
    "unavailable",
    "available",
};

// esp_hf_roaming_status_t
const char *c_roaming_status_str[] = {
    "inactive",
    "active",
};

// esp_hf_client_call_state_t
const char *c_call_str[] = {
    "NO call in progress",
    "call in progress",
};

// esp_hf_client_callsetup_t
const char *c_call_setup_str[] = {"NONE", "INCOMING", "OUTGOING_DIALING", "OUTGOING_ALERTING"};

// esp_hf_client_callheld_t
const char *c_call_held_str[] = {
    "NONE held",
    "Held and Active",
    "Held",
};

// esp_hf_response_and_hold_status_t
const char *c_resp_and_hold_str[] = {
    "HELD",
    "HELD ACCEPTED",
    "HELD REJECTED",
};

// esp_hf_client_call_direction_t
const char *c_call_dir_str[] = {
    "outgoing",
    "incoming",
};

// esp_hf_client_call_state_t
const char *c_call_state_str[] = {
    "active", "held", "dialing", "alerting", "incoming", "waiting", "held_by_resp_hold",
};

// esp_hf_current_call_mpty_type_t
const char *c_call_mpty_type_str[] = {
    "single",
    "multi",
};

// esp_hf_volume_control_target_t
const char *c_volume_control_target_str[] = {"SPEAKER", "MICROPHONE"};

// esp_hf_at_response_code_t
const char *c_at_response_code_str[] = {
    "OK",
    "ERROR"
    "ERR_NO_CARRIER",
    "ERR_BUSY",
    "ERR_NO_ANSWER",
    "ERR_DELAYED",
    "ERR_BLACKLILSTED",
    "ERR_CME",
};

// esp_hf_subscriber_service_type_t
const char *c_subscriber_service_type_str[] = {
    "unknown",
    "voice",
    "fax",
};

// esp_hf_client_in_band_ring_state_t
const char *c_inband_ring_state_str[] = {
    "NOT provided",
    "Provided",
};

static void bt_app_hf_client_audio_open(void) {
    ESP_LOGE(BT_HF_TAG, "bt_app_hf_client_audio_open");
    int sample_rate = HFP_RESAMPLE_RATE;
    audio_element_info_t bt_info = {0};
    audio_element_getinfo(bt_stream_reader, &bt_info);
    bt_info.sample_rates = sample_rate;
    bt_info.channels = 1;
    bt_info.bits = 16;
    audio_element_setinfo(bt_stream_reader, &bt_info);
    audio_element_report_info(bt_stream_reader);
}

static void bt_app_hf_client_audio_close(void) {
    ESP_LOGE(BT_HF_TAG, "bt_app_hf_client_audio_close");
    int sample_rate = periph_bluetooth_get_a2dp_sample_rate();
    audio_element_info_t bt_info = {0};
    audio_element_getinfo(bt_stream_reader, &bt_info);
    bt_info.sample_rates = sample_rate;
    bt_info.channels = 2;
    bt_info.bits = 16;
    audio_element_setinfo(bt_stream_reader, &bt_info);
    audio_element_report_info(bt_stream_reader);
}

static uint32_t bt_app_hf_client_outgoing_cb(uint8_t *p_buf, uint32_t sz) {
    int out_len_bytes = 0;
    char *enc_buffer = (char *)audio_malloc(sz);
    AUDIO_MEM_CHECK(BT_HF_TAG, enc_buffer, return 0);
    if (is_get_hfp) {
        out_len_bytes = raw_stream_read(raw_read, enc_buffer, sz);
    }

    if (out_len_bytes == sz) {
        is_get_hfp = false;
        memcpy(p_buf, enc_buffer, out_len_bytes);
        free(enc_buffer);
        return sz;
    } else {
        is_get_hfp = true;
        free(enc_buffer);
        return 0;
    }
}

static void bt_app_hf_client_incoming_cb(const uint8_t *buf, uint32_t sz) {
    if (bt_stream_reader) {
        if (audio_element_get_state(bt_stream_reader) == AEL_STATE_RUNNING) {
            audio_element_output(bt_stream_reader, (char *)buf, sz);
            esp_hf_client_outgoing_data_ready();
        }
    }
}

/* callback for HF_CLIENT */
void bt_hf_client_cb(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param) {
    if (event <= ESP_HF_CLIENT_RING_IND_EVT) {
        ESP_LOGE(BT_HF_TAG, "APP HFP event: %s", c_hf_evt_str[event]);
    } else {
        ESP_LOGE(BT_HF_TAG, "APP HFP invalid event %d", event);
    }

    switch (event) {
    case ESP_HF_CLIENT_CONNECTION_STATE_EVT:
        ESP_LOGE(BT_HF_TAG, "--connection state %s, peer feats 0x%" PRIx32 ", chld_feats 0x%" PRIx32,
                 c_connection_state_str[param->conn_stat.state], param->conn_stat.peer_feat, param->conn_stat.chld_feat);
        break;
    case ESP_HF_CLIENT_AUDIO_STATE_EVT:
        ESP_LOGE(BT_HF_TAG, "--audio state %s", c_audio_state_str[param->audio_stat.state]);
#if CONFIG_HFP_AUDIO_DATA_PATH_HCI
        if ((param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_CONNECTED) ||
            (param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC)) {
            bt_app_hf_client_audio_open();
            esp_hf_client_register_data_callback(bt_app_hf_client_incoming_cb, bt_app_hf_client_outgoing_cb);
        } else if (param->audio_stat.state == ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED) {
            bt_app_hf_client_audio_close();
        }
#endif /* #if CONFIG_HFP_AUDIO_DATA_PATH_HCI */
        break;
    case ESP_HF_CLIENT_BVRA_EVT:
        ESP_LOGE(BT_HF_TAG, "--VR state %s", c_vr_state_str[param->bvra.value]);
        break;
    case ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT:
        ESP_LOGE(BT_HF_TAG, "--NETWORK STATE %s", c_service_availability_status_str[param->service_availability.status]);
        break;
    case ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT:
        ESP_LOGE(BT_HF_TAG, "--ROAMING: %s", c_roaming_status_str[param->roaming.status]);
        break;
    case ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT:
        ESP_LOGE(BT_HF_TAG, "-- signal strength: %d", param->signal_strength.value);
        break;
    case ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT:
        ESP_LOGE(BT_HF_TAG, "--battery level %d", param->battery_level.value);
        break;
    case ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT:
        ESP_LOGE(BT_HF_TAG, "--operator name: %s", param->cops.name);
        break;
    case ESP_HF_CLIENT_CIND_CALL_EVT:
        ESP_LOGE(BT_HF_TAG, "--Call indicator %s", c_call_str[param->call.status]);
        break;
    case ESP_HF_CLIENT_CIND_CALL_SETUP_EVT:
        ESP_LOGE(BT_HF_TAG, "--Call setup indicator %s", c_call_setup_str[param->call_setup.status]);
        break;
    case ESP_HF_CLIENT_CIND_CALL_HELD_EVT:
        ESP_LOGE(BT_HF_TAG, "--Call held indicator %s", c_call_held_str[param->call_held.status]);
        break;
    case ESP_HF_CLIENT_BTRH_EVT:
        ESP_LOGE(BT_HF_TAG, "--response and hold %s", c_resp_and_hold_str[param->btrh.status]);
        break;
    case ESP_HF_CLIENT_CLIP_EVT:
        ESP_LOGE(BT_HF_TAG, "--clip number %s", (param->clip.number == NULL) ? "NULL" : (param->clip.number));
        break;
    case ESP_HF_CLIENT_CCWA_EVT:
        ESP_LOGE(BT_HF_TAG, "--call_waiting %s", (param->ccwa.number == NULL) ? "NULL" : (param->ccwa.number));
        break;
    case ESP_HF_CLIENT_CLCC_EVT:
        ESP_LOGE(BT_HF_TAG, "--Current call: idx %d, dir %s, state %s, mpty %s, number %s", param->clcc.idx,
                 c_call_dir_str[param->clcc.dir], c_call_state_str[param->clcc.status], c_call_mpty_type_str[param->clcc.mpty],
                 (param->clcc.number == NULL) ? "NULL" : (param->clcc.number));
        break;
    case ESP_HF_CLIENT_VOLUME_CONTROL_EVT:
        ESP_LOGE(BT_HF_TAG, "--volume_target: %s, volume %d", c_volume_control_target_str[param->volume_control.type],
                 param->volume_control.volume);
        break;
    case ESP_HF_CLIENT_AT_RESPONSE_EVT:
        ESP_LOGE(BT_HF_TAG, "--AT response event, code %d, cme %d", param->at_response.code, param->at_response.cme);
        break;
    case ESP_HF_CLIENT_CNUM_EVT:
        ESP_LOGE(BT_HF_TAG, "--subscriber type %s, number %s", c_subscriber_service_type_str[param->cnum.type],
                 (param->cnum.number == NULL) ? "NULL" : param->cnum.number);
        break;
    case ESP_HF_CLIENT_BSIR_EVT:
        ESP_LOGE(BT_HF_TAG, "--inband ring state %s", c_inband_ring_state_str[param->bsir.state]);
        break;
    case ESP_HF_CLIENT_BINP_EVT:
        ESP_LOGE(BT_HF_TAG, "--last voice tag number: %s", (param->binp.number == NULL) ? "NULL" : param->binp.number);
        break;
    default:
        ESP_LOGE(BT_HF_TAG, "HF_CLIENT EVT: %d", event);
        break;
    }
}

#endif

// 蓝牙事件回调
static void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) {
    uint8_t *bda = NULL;
    switch (event) {
    case ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT:
        bda = (uint8_t *)param->acl_conn_cmpl_stat.bda;
        snprintf(devInfo.BTInfo.mac_str, sizeof(devInfo.BTInfo.mac_str), "%02x:%02x:%02x:%02x:%02x:%02x", bda[0], bda[1], bda[2], bda[3],
                 bda[4], bda[5]);
        ESP_LOGI(TAG, "ESP_BT_GAP_AUTH_CMPL_EVT Connected to [%s], status: 0x%x", devInfo.BTInfo.mac_str, param->auth_cmpl.stat);
        devInfo.BTInfo.connState = true;
        memcpy(devInfo.BTInfo.mac, bda, sizeof(esp_bd_addr_t));
        nvs_write("bt_addr", devInfo.BTInfo.mac_str);
        break;
    case ESP_BT_GAP_AUTH_CMPL_EVT:
        // 认证结果处理
        break;
    case ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT:
        bda = (uint8_t *)param->acl_disconn_cmpl_stat.bda;
        ESP_LOGI(TAG, "ESP_BT_GAP_ACL_DISC_CMPL_STAT_EVT Disconnected from [%02x:%02x:%02x:%02x:%02x:%02x], reason: 0x%x", bda[0], bda[1],
                 bda[2], bda[3], bda[4], bda[5], param->acl_disconn_cmpl_stat.reason);
        esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
        devInfo.BTInfo.connState = false;
        discovery_timeout = BT_AUTO_DISCOVERY_TIMEOUT;
        break;
    /* others */
    default: {
        ESP_LOGI(TAG, "event: %d", event);
        break;
    }
    }
    return;
}

// 周期处理函数
static void user_bt_period_handler() {
    static int count_100ms = 0;
    if (count_100ms++ % 30 == 0) {
        if (devInfo.BTInfo.connState) {
            ESP_LOGI(TAG, "Bluetooth is connected");
        } else {
            ESP_LOGI(TAG, "Bluetooth is disconnected");
            esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
        }
    }
}

esp_periph_handle_t bt_periph;
static audio_element_info_t music_info;

void user_bt_init() {
    ESP_LOGI(TAG, "[ 1 ] Create Bluetooth service");
    bluetooth_service_cfg_t bt_cfg = {
        .device_name = devInfo.deviceName,
        .mode = BLUETOOTH_A2DP_SINK,
    };
    bluetooth_service_start(&bt_cfg);
    esp_hf_client_register_callback(bt_hf_client_cb);
    esp_hf_client_init();

    ESP_LOGI(TAG, "[ 4 ] Initialize peripherals");
    esp_periph_config_t periph_cfg = DEFAULT_ESP_PERIPH_SET_CONFIG();
    esp_periph_set_handle_t set = esp_periph_set_init(&periph_cfg);

    ESP_LOGI(TAG, "[4.2] Create Bluetooth peripheral");
    bt_periph = bluetooth_service_create_periph();

    ESP_LOGI(TAG, "[4.2] Start all peripherals");
    esp_periph_start(set, bt_periph);
    esp_bt_gap_register_callback(bt_app_gap_cb);

    vTaskDelay(1000 / portTICK_PERIOD_MS);

    if (strlen(devInfo.BTInfo.mac_str) > 0) {
        esp_a2d_sink_connect(devInfo.BTInfo.mac);
    } else {
        ESP_LOGI(TAG, "don't connect to any device, please set the mac address first");
    }
}

// 配置音频状态
void user_bt_audio_config(user_bt_cmd_t cmd) {
    switch (cmd) {
    case USER_BT_PAUSE:
        if (devInfo.BTInfo.connState) {
            periph_bluetooth_pause(bt_periph);
            ESP_LOGI(TAG, "[ * ] Bluetooth paused");
        }
        break;
    case USER_BT_RESUME:
        if (devInfo.BTInfo.connState) {
            periph_bluetooth_play(bt_periph);
            ESP_LOGI(TAG, "[ * ] Bluetooth resumed");
        }
        break;
    default:
        break;
    }
}

// 连接蓝牙设备
void user_bt_connect(bool is_default_mac, uint8_t remote_addr[6]) {
    if (devInfo.BTInfo.connState) {
        ESP_LOGI(TAG, "[ * ] Bluetooth already connected, disconnect first");
        user_bt_disconnect();
    }

    esp_bd_addr_t addr = {0};
    is_default_mac ? memcpy(addr, devInfo.BTInfo.mac, sizeof(esp_bd_addr_t)) : memcpy(addr, remote_addr, sizeof(esp_bd_addr_t));

    esp_a2d_sink_connect(addr);
    ESP_LOGI(TAG, "[ * ] Bluetooth try to connect dev:[%02x:%02x:%02x:%02x:%02x:%02x]", addr[0], addr[1], addr[2], addr[3], addr[4],
             addr[5]);
}

// 断开蓝牙设备
void user_bt_disconnect(void) {
    if (devInfo.BTInfo.connState) {
        esp_a2d_sink_disconnect(devInfo.BTInfo.mac);
        devInfo.BTInfo.connState = false;
        ESP_LOGI(TAG, "[ * ] Bluetooth disconnected");
    } else {
        ESP_LOGI(TAG, "[ * ] Bluetooth already disconnected");
    }
}

// 配置为可发现
void user_bt_discovery_config(bool enable) {
    if (enable) {
        esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
        ESP_LOGI(TAG, "[ * ] Bluetooth discovery enabled");
    } else {
        esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
        ESP_LOGI(TAG, "[ * ] Bluetooth discovery disabled");
    }
}